package com.jiaoshouMr.ethereum.service.impl;

import com.jiaoshouMr.ethereum.domain.BlockAccount;
import com.jiaoshouMr.ethereum.domain.GhostBlockAccount;
import com.jiaoshouMr.ethereum.repository.BlockRepository;
import com.jiaoshouMr.ethereum.repository.EthRepository;
import com.jiaoshouMr.ethereum.service.EthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class EthServiceImpl implements EthService {
    @Autowired
    private EthRepository ethRepository;

    @Autowired
    private BlockRepository blockRepository;

    @Override
    public Map<String, Object> getAccount(String ghostId, String type) {
        //小鬼是否存在
        Map ghost = ethRepository.findGhost(ghostId);
        Map<String, Object> result = new HashMap<>();
        if (!type.equals("eth")) {
            result.put("status", -1);
            result.put("msg", "年轻人不要搞事情");
            return result;
        }
        if (ghost == null) {
            result.put("status", -1);
            result.put("msg", "ghostId 不存在");
            return result;
        }
        //是否已经有小鬼以太坊账号
        GhostBlockAccount eth = ethRepository.getAccount(ghostId, type);
        if (eth == null) {
            BlockAccount blockAccount = blockRepository.getAccount(type);
            GhostBlockAccount ghostBlockAccount = new GhostBlockAccount();
            ghostBlockAccount.setAccount(blockAccount.getAccount());
            ghostBlockAccount.setGhostId(ghostId);
            ghostBlockAccount.setAmount(new Double("0.0000"));
            ghostBlockAccount.setType(type);
            ethRepository.bindEthAccount(ghostBlockAccount);
            result.put("account", blockAccount.getAccount());
            blockRepository.updateFirst(blockAccount.getId());
        } else {
            result.put("account", eth.getAccount());
        }
        result.put("status", 0);
        result.put("msg", "successful");
        return result;
    }
}
